package cn.wolfcode.trip.base.util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传工具
 */
public class UploadUtil {

    /**
     * 处理文件上传
     *
     * @param file
     * @param basePath
     * @return 123.png
     */
    public static final String UPLOADPATH = "D:/trip";

    //七牛云域名
    public static final String QINIU_PATH = "http://plb9q9krt.bkt.clouddn.com/";

    public static final String QINIU_UPLOAD = "/qiniuUpload/";


    public static String upload(MultipartFile file, String basePath) {


        String uuid = UUID.randomUUID().toString();

        String orgFileName = file.getOriginalFilename();
        String ext = "." + FilenameUtils.getExtension(orgFileName);
        String fileName = uuid + ext;
        try {
            File targetFile = new File(UPLOADPATH + basePath, fileName);
            FileUtils.writeByteArrayToFile(targetFile, file.getBytes());

            return "/upload/" + fileName;

        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }


    /**
     * 上传到七牛云
     *
     * @param file
     * @return
     */
    public static String uploadQiniu(MultipartFile file) {
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone2());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        String accessKey = "Lg8Bkem0U00Xnd4luspXqR9V3s-OJyxY__emhlcn";
        String secretKey = "gkWMmkSMPvt_nNpB5xsJ8TTPhohhymwWE7w57kSk";
        String bucket = "trip29";
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = null;//上传到服务器的文件名称(uuid)
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(file.getBytes(), key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);//文件名称
            System.out.println(putRet.hash);
            return QINIU_UPLOAD + putRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


        return null;
    }


}
























